package com.hdaccp.letting.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

//@Configuration
//@ConfigurationProperties(prefix = "jdbc")
public class MyBatisConfig {
    private String driver ;
    private String url ;
    private String uname ;
    private String password ;
   // @Bean
    public DataSource getDataSource(){
        DruidDataSource ds = new DruidDataSource() ;
        ds.setPassword(password);
        ds.setUsername(uname);
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        return ds ;
    }

   // @Bean
   // @ConditionalOnMissingBean
    public SqlSessionFactoryBean getSqlSessionFactoryBean(){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean() ;
        sqlSessionFactoryBean.setDataSource(getDataSource());
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver() ;
        try {
            sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mybatis/mapper/*.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactoryBean.setTypeAliasesPackage("com.hdaccp.letting.bean.entity");
        return sqlSessionFactoryBean ;
    }
    //@Configuration
   // @AutoConfigureAfter(SqlSessionFactoryBean.class)
    public static class ScanDao{
        @Bean
        public MapperScannerConfigurer getMapperScannerConfigurer(){
            MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer() ;
            mapperScannerConfigurer.setBasePackage("com.hdaccp.letting.dao");
            return mapperScannerConfigurer ;
        }
    }
}
